package cn.interestingshop.dao;

import cn.interestingshop.entity.OrderInfo;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class OrderInfoDaoImpl extends BaseDaoImpl implements OrderInfoDao {
    public OrderInfoDaoImpl(Connection connection) {
        super(connection);
    }

    @Override
    public List<OrderInfo> createEntityByResultSet(ResultSet rs) throws Exception {

        List<OrderInfo> list=new ArrayList<>();

        while (rs.next()){
            OrderInfo orderInfo=new OrderInfo();

            orderInfo.setId(rs.getInt("id"));
            orderInfo.setAmount(rs.getFloat("amount"));
            orderInfo.setBuyNum(rs.getInt("buy_num"));
            orderInfo.setGoodsId(rs.getInt("goods_id"));
            orderInfo.setBaseOrderId(rs.getInt("base_order_id"));

            list.add(orderInfo);
        }

        return list;
    }

    @Override
    public int insert(OrderInfo orderInfo) {
        int rs=0;

        try {
            String sql = "INSERT INTO `interesting_shop_db`.`t_order_info`(`base_order_id`, `goods_id`, `buy_num`, `amount`) VALUES (?,?,?,?)";
            Object[] objects = new Object[]{orderInfo.getBaseOrderId(),orderInfo.getGoodsId(),orderInfo.getBuyNum(),orderInfo.getAmount()};
            rs = executeInsert(sql, objects);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            closeResource();
        }

        return rs;
    }

    @Override
    public List<OrderInfo> selectOne(int id) {

        ResultSet rs=null;
        List<OrderInfo> list=new ArrayList<>();

        String sql="select b.id,b.base_order_id,b.goods_id,b.buy_num,b.amount from t_base_order a,t_order_info b where b.base_order_id=a.id and a.id=?";
        Object[] objects=new Object[]{id};

        rs=executeQuery(sql,objects);
        try {
            list=createEntityByResultSet(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            closeResource();
            closeResource(rs);
        }

        return list;
    }
}
